package com.wh.base.util;

import java.io.UnsupportedEncodingException;

import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;

public class PwdUtil {
	
	/**
	 * 生成密码加密用的盐值
	 * @return
	 */
	public static byte[] createSalt(byte[] srcData){
		SM3Digest digest = new SM3Digest();
	    digest.update(srcData, 0, srcData.length);
	    byte[] hash = new byte[digest.getDigestSize()];
	    digest.doFinal(hash, 0);
	    return hash;
	}
	
	/**
	 * 加密密码
	 * @param password
	 * @param salt
	 * @return
	 */
	public static String encryptPwd(String password){
		// 将返回的hash值转换成16进制字符串
	    String resultHexString = "";
	    try {
	        // 将字符串转换成byte数组
	        byte[] srcData = password.getBytes("UTF-8");
	        // 调用hash()
	        byte[] resultHash = createSalt(srcData);
	        // 将返回的hash值转换成16进制字符串
	        resultHexString = ByteUtils.toHexString(resultHash);
	    } catch (UnsupportedEncodingException e) {
	        e.printStackTrace();
	    }
	    return resultHexString;
	}
	
	/**
	 * 比较密码是否正确
	 * @param newPwd  未加密的密码
	 * @param salt    加密密码时的盐值
	 * @param oldPwd  加密成功后的密码
	 * @return
	 */
	public static boolean comparisonPwd(String newPwd, String oldPwd){
		if(StringUtil.isEmpty(newPwd)){
			return false;
		}
		
		String encryptPwd = encryptPwd(newPwd.trim());
		if(oldPwd.equals(encryptPwd)){
			return true;
		}else{
			return false;
		}
		
	}
	
	public static void main(String[] args) {
		System.out.println(encryptPwd("123456"));
	}

}
